import json
import random, re
import time,requests

import redis
from django.http import HttpResponse

from flask import Blueprint, jsonify, request, make_response, redirect
from flask_restful import reqparse, Api

#导入支付基类
from utils.pay import AliPay

from utils.MySms import SmsTool
from utils.myredis import r
from utils.db import db
from utils.MyJwt import JwtTool
from utils.captcha.captcha import captcha
from models.model import Sflogin,User

top_bp = Blueprint('top_bp', __name__, url_prefix='/top')
api = Api(top_bp)



# 支付宝平台
from utils.projectcom import get_ali_object
from utils.snowflake import IdWorker
from models.model import Top_up

# 充值
@top_bp.route('/alipay', methods=['GET', 'POST'])
def getalipay():
    # 获取数据
    req = reqparse.RequestParser()
    req.add_argument("user_id", type=int, required=True)
    req.add_argument("money", type=int, required=True)
    args = req.parse_args()

    worker = IdWorker(random.randint(0, 9), random.randint(0, 9), random.randint(0, 9))
    code = str(worker.get_id)
    print("1111111111111", code)

    # return_url = "http://localhost:8000/top_bp/callback?user_id=" + str(args["user_id"])
    # print("2222222222222", return_url)

    alipay = get_ali_object(args['user_id'])
    res = alipay.direct_pay(subject='充值',  # 商品描述
                            out_trade_no=code,  # 用户购买的商品订单号
                            total_amount=args['money'], # 交易金额
                            # return_url=None,
                            user_id=args['user_id'])


    pay_url = f"https://openapi.alipaydev.com/gateway.do?{res}"

    # return redirect(pay_url)    # 访问是跳转到pay_url页面
    return jsonify({'code': 200, 'url': pay_url})


# 回调接口
@top_bp.route('/callback')
def callback():
    print("----------------")
    user_id = request.args.get('user_id')
    money = request.args.get('total_amount')
    code = request.args.get('out_trade_no')


    print("22222222222",type(user_id))
    print(type(money))
    print(type(code))

    sql = "select * from user where id='%s'" %user_id
    aa = db.find(sql)
    print("----------------")
    # 添加充值表
    sql = "insert into top_up (user_id, money, status, code) values ('%s','%s',%d,'%s')" %(user_id, money, 0, code)
    db.update(sql)


    sum = float(aa['money'])+float(money)
    print(aa['money'])
    print(money)
    print(sum)

    user_info = "update user set money='%s' where id='%s'" % (sum, user_id)
    db.find(user_info)
    # db.commit()





    # 从定向
    return redirect("http://localhost:8080/zhuye")


# prjnyh7813@sandbox.com



